package com.yanqu.road.dao.impl.activity.share;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserShareGoodsData;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ShareGoodsDaoImpl extends TempDataObjectDao<UserShareGoodsData> {
    public static String getUserShareDataSql = "select * from `t_u_share_goods` where `userId`=?";

    public Map<Integer,UserShareGoodsData> getUserShareData(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, UserShareGoodsData> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(getUserShareDataSql);
            int i = 1;
            call.setLong(i++, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserShareGoodsData data = parse(rs);
                dataMap.put(data.getGoodsId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected boolean updateData(UserShareGoodsData userShareData) {
        return true;
    }

    public static String insertUserShareDataSql = "insert into `t_u_share_goods`(userId,goodsId,rewardTime) values (?,?,?)";

    @Override
    protected boolean addData(UserShareGoodsData userShareData) {
        userShareData.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, userShareData.getUserId()));
        para.put(i++, new DbParameter(Types.INTEGER, userShareData.getGoodsId()));
        para.put(i++, new DbParameter(Types.BIGINT, userShareData.getRewardTime()));
        if (getDb().executeNoneQuery(insertUserShareDataSql, para) > 0) {
            return true;
        }
        return false;

    }

    @Override
    protected UserShareGoodsData parseData(ResultSet rs) throws SQLException {
        UserShareGoodsData data = new UserShareGoodsData();
        data.setUserId(rs.getLong("userId"));
        data.setGoodsId(rs.getInt("goodsId"));
        data.setRewardTime(rs.getLong("rewardTime"));

        return data;
    }


}
